<template>
  <div>
    <a-page-header>
      <a-steps :current="state">
        <a-step title="上传"/>
        <a-step title="运行"/>
        <a-step title="结果"/>
      </a-steps>
    </a-page-header>
    <a-result>
      <template #icon>


        <template v-if="state===0">
          <a-upload-dragger
              :multiple="true"
              action="/upload"
              name="file"
              @change="handleUploadChange"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox"/>
            </p>
            <p class="ant-upload-text">
              点击此处或拖拽文件上传
            </p>
          </a-upload-dragger>
        </template>

        <template v-else-if="state===1">
          <a-result title="正在运行，请稍等">
            <template #icon>
              <a-icon style="color: #1890FF" type="loading"/>
            </template>
            <template #extra>
              <p>本次任务ID：{{ fileId }}
                <br/>
                您可以保存此ID并在稍后手动查询结果
              </p>
            </template>
          </a-result>
        </template>

        <template v-else-if="state===2">
          <a-space v-if="outcome!==''" direction="vertical">
            <a-alert :message="outcome" :type="outcome==='Success'?'success':'warning'" show-icon/>
            <img :src="resultPicture"/>
            <a-button v-if="outcome==='Success'" type="primary" @click="download">保存详细结果</a-button>
          </a-space>
        </template>


      </template>
    </a-result>
  </div>
</template>

<script>
let interval = ""
export default {
  name: "Home",
  data() {
    return {
      state: 0, //状态机状态
      fileId: "", //文件编号
      outcome: "", //结果文本
      resultPicture: "", //结果图片URL
    };
  },
  methods: {
    handleUploadChange(change) {
      if (change.file.status === "done") {
        this.state = 1
        this.fileId = change.file.response.payload.split(".")[0]
        interval = setInterval(async () => {
          let res = await fetch("/query?filename=" + this.fileId)
          let json = await res.json()
          if (json.status) {
            this.outcome = json.payload

            clearInterval(interval)
            interval = ""

            //如果结果为成功则显示图片
            if (this.outcome === "Success") {
              this.resultPicture = "/output/" + this.fileId + ".png"
            }

            this.state = 2
          }
        }, 1000)
      }
    },
    download(){
      window.open("/output/" + this.fileId + ".xls")
    }
  },
  destroyed() {
    if (interval !== "") clearInterval(interval)
  }
};
</script>
